import { store } from "@mall/api-services"
import { Button, Card, Col, Divider, Form, Input, Modal, PageHeader, Popconfirm, Row, Table } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useCallback, useEffect, useState } from "react"
import { useParams } from "react-router-dom"

import classes from "./custom-collection-list.module.scss"

interface CustomCollectionFormProps {
  customCollection?: store.CustomCollection
  onFinish?: (values: store.CustomCollection) => void
}

function CustomCollectionForm(props: CustomCollectionFormProps) {

  const { customCollection } = props
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  }
  const tailLayout = {
    wrapperCol: { offset: 5, span: 18 },
  }

  const [form] = Form.useForm()

  useEffect(() =>
      form.setFieldsValue(_.isUndefined(customCollection) ? {} : customCollection),
    [form, customCollection])

  function onFinish(values: any) {
    if (_.isFunction(props.onFinish)) {
      props.onFinish(_.assign(new store.CustomCollection(), customCollection, values))
    }
  }

  return (
    <Form  {...layout} form={form}
           onFinish={onFinish}>
      <Form.Item
        label="集合名称"
        name="name"
        rules={[{ required: true, message: "请输入集合名称!" }]}>
        <Input/>
      </Form.Item>
      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">保存</Button>
      </Form.Item>
    </Form>
  )

}

export default function CustomCollectionList() {
  const { storeId = "" } = useParams()
  const [customCollections, setCustomCollections] = useState(([] as store.CustomCollection[]))
  const [currentCollection, setCurrentCollection] = useState(new store.CustomCollection())
  const [newModalVisible, setNewModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [loading, setLoading] = useState(false)

  const refreshCollections =
    useCallback(() =>
      store.CollectionServiceV1
        .getCollections(storeId)
        .then(setCustomCollections), [storeId])

  useEffect(() => {
    setLoading(true)
    refreshCollections().then(() => setLoading(false))
  }, [refreshCollections, storeId])

  function onNewCustomCollection(collection: store.CustomCollection) {
    setLoading(true)
    store.CollectionServiceV1
      .createCollection(storeId, collection)
      .then(refreshCollections)
      .finally(() => setNewModalVisible(false))
      .finally(() => setLoading(false))
  }

  function onUpdateCustomCollection(collection: store.CustomCollection) {
    setLoading(true)
    store.CollectionServiceV1
      .saveCollection(storeId, collection)
      .then(refreshCollections)
      .finally(() => setEditModalVisible(false))
      .finally(() => setLoading(false))
  }

  function onDeleteCustomCollection(id: any) {
    setLoading(true)
    store.CollectionServiceV1
      .deleteCollection(storeId, id)
      .finally(() => refreshCollections())
      .finally(() => setLoading(false))
  }

  const columns = [
    {
      title: "分组名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "商品数",
      dataIndex: "products",
      key: "products",
      width: "120px",
    },
    {
      title: "创建时间",
      dataIndex: "createdTime",
      key: "createdTime",
      width: "200px",
    },
    {
      title: "操作",
      key: "actions",
      width: "200px",
      render: (text: string, record: store.CustomCollection) => (
        <>
          <Button type="link" size="small" style={{ margin: 0 }}
                  onClick={() => {
                    setCurrentCollection(record)
                    setEditModalVisible(true)
                  }}>修改</Button>
          <Divider type="vertical"/>
          <Popconfirm
            placement="bottomRight"
            onConfirm={() => onDeleteCustomCollection(record.id)}
            title="确定删除这个商品?">
            <Button type="link" size="small" style={{ margin: 0 }}>删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ]


  return (
    <div className={classes.collectionList}>
      <PageHeader title="商品集合" ghost={false}/>
      <Card className={classes.collectionListContent}>
        <Row gutter={[16, 16]}>
          <Col><Button type="primary" onClick={() => setNewModalVisible(true)}>新建商品集合</Button></Col>
          <Modal visible={newModalVisible}
                 title="新建商品集合"
                 onCancel={() => setNewModalVisible(false)}
                 footer={false}>
            <CustomCollectionForm onFinish={onNewCustomCollection}/>
          </Modal>
          <Modal visible={editModalVisible}
                 title="编辑商品集合"
                 onCancel={() => setEditModalVisible(false)}
                 footer={false}>
            <CustomCollectionForm customCollection={currentCollection} onFinish={onUpdateCustomCollection}/>
          </Modal>
        </Row>
        <Row>
          <Col span={24}>
            <Table rowKey="id"
                   loading={loading}
                   dataSource={customCollections}
                   columns={columns}/>
          </Col>
        </Row>
      </Card>
    </div>
  )
}
